// 侧边栏
(function() {
    'use strict';

    if (!window.DUAL_SIDEBAR_PARTICLE) {
        window.DUAL_SIDEBAR_PARTICLE = (function() {
            // =============== 配置参数 ================
            const CONFIG = {
                SIDEBAR_WIDTH: 80,          // 单侧边栏宽度
                PARTICLE_COUNT: 120,         // 每侧粒子数量
                LINE_STEP: 10,              // 连线步长(每n个粒子连接)
                MOUSE_INFLUENCE: 0.1,       // 鼠标影响系数
                RANDOM_FORCE: 0.03,         // 随机运动强度
                GATHER_FORCE: 0.1,          // 聚拢力度
                SCATTER_FORCE: 0.8,         // 打散力度
                BLUR_STRENGTH: 12,          // 毛玻璃强度
                PARTICLE_COLOR: [200, 220, 255], // 粒子颜色
                CONTAINER_OPACITY: 0.25      // 容器透明度
            };

            // =============== 核心逻辑 ================
            class ParticleSidebar {
                constructor(side) {
                    this.side = side;
                    this.container = null;
                    this.canvas = null;
                    this.ctx = null;
                    this.particles = [];
                    this.mouse = { x: null, y: null, active: false };
                    this.animationFrameId = null;
                    this.initContainer();
                    this.initCanvas();
                    this.createParticles();
                    this.initEvents();
                    this.animate();
                }

                // 创建容器
                initContainer() {
                    this.container = document.createElement('div');
                    this.container.style.cssText = `
                        position: fixed;
                        top: 0;
                        ${this.side === 'left' ? 'left: 0;' : 'right: 0;'}
                        width: ${CONFIG.SIDEBAR_WIDTH}px;
                        height: 100vh;
                        background: rgba(255, 255, 255, ${CONFIG.CONTAINER_OPACITY});
                        backdrop-filter: blur(${CONFIG.BLUR_STRENGTH}px);
                        border-${this.side === 'left' ? 'right' : 'left'}: 1px solid rgba(255, 255, 255, 0.15);
                        box-shadow: ${this.side === 'left' ? '2px' : '-2px'} 0 12px rgba(0, 0, 0, 0.1);
                        z-index: 9999;
                        pointer-events: auto;
                    `;
                    document.body.appendChild(this.container);
                }

                // 初始化画布
                initCanvas() {
                    this.canvas = document.createElement('canvas');
                    this.canvas.style.cssText = `
                        position: absolute;
                        top: 0;
                        left: 0;
                        pointer-events: none;
                    `;
                    this.container.appendChild(this.canvas);
                    this.ctx = this.canvas.getContext('2d');
                    this.updateSize();
                }

                // 更新尺寸
                updateSize() {
                    this.canvas.width = CONFIG.SIDEBAR_WIDTH;
                    this.canvas.height = window.innerHeight;
                }

                // 创建粒子
                createParticles() {
                    this.particles = Array.from({ length: CONFIG.PARTICLE_COUNT }, (_, i) => ({
                        x: Math.random() * CONFIG.SIDEBAR_WIDTH,
                        y: Math.random() * window.innerHeight,
                        xa: (Math.random() - 0.5) * 0.8,
                        ya: (Math.random() - 0.5) * 0.8,
                        angle: (i / CONFIG.PARTICLE_COUNT) * Math.PI * 2
                    }));
                }

                // 动画循环
                animate() {
                    const { ctx } = this;
                    ctx.clearRect(0, 0, CONFIG.SIDEBAR_WIDTH, window.innerHeight);

                    // 设置绘图样式
                    ctx.fillStyle = `rgb(${CONFIG.PARTICLE_COLOR.join(',')})`;
                    ctx.strokeStyle = `rgba(${CONFIG.PARTICLE_COLOR.join(',')}, 0.2)`;

                    this.particles.forEach((particle, i) => {
                        // 添加随机运动
                        particle.xa += (Math.random() - 0.5) * CONFIG.RANDOM_FORCE;
                        particle.ya += (Math.random() - 0.5) * CONFIG.RANDOM_FORCE;

                        // 边界反弹
                        if (particle.x < 0 || particle.x > CONFIG.SIDEBAR_WIDTH) {
                            particle.xa *= -0.8;
                            particle.x = Math.max(0, Math.min(CONFIG.SIDEBAR_WIDTH, particle.x));
                        }
                        if (particle.y < 0 || particle.y > window.innerHeight) {
                            particle.ya *= -0.8;
                            particle.y = Math.max(0, Math.min(window.innerHeight, particle.y));
                        }

                        // 更新位置
                        particle.x += particle.xa;
                        particle.y += particle.ya;

                        // 绘制粒子
                        ctx.fillRect(particle.x-1, particle.y-1, 2, 2);

                        // 鼠标交互
                        if (this.mouse.active) {
                            const targetX = this.mouse.x + Math.cos(particle.angle) * 30;
                            const targetY = this.mouse.y + Math.sin(particle.angle) * 30;
                            const dx = targetX - particle.x;
                            const dy = targetY - particle.y;
                            particle.xa += dx * CONFIG.GATHER_FORCE;
                            particle.ya += dy * CONFIG.GATHER_FORCE;
                        }

                        // 步进式连线
                        for (let step = CONFIG.LINE_STEP; step < CONFIG.PARTICLE_COUNT; step += CONFIG.LINE_STEP) {
                            const targetIndex = (i + step) % CONFIG.PARTICLE_COUNT;
                            const target = this.particles[targetIndex];
                            const dx = particle.x - target.x;
                            const dy = particle.y - target.y;
                            const distSq = dx*dx + dy*dy;

                            if (distSq < 6000) {
                                ctx.beginPath();
                                ctx.moveTo(particle.x, particle.y);
                                ctx.lineTo(target.x, target.y);
                                ctx.stroke();
                            }
                        }
                    });

                    // 速度衰减
                    this.particles.forEach(p => {
                        // p.xa *= 0.97;
                        // p.ya *= 0.97;

                        p.xa *= 1.0;
                        p.ya *= 1.0;
                    });

                    this.animationFrameId = requestAnimationFrame(() => this.animate());
                }

                // 事件监听
                initEvents() {
                    // // 鼠标移动
                    // this.container.addEventListener('mousemove', (e) => {
                    //     const rect = this.container.getBoundingClientRect();
                    //     this.mouse.x = e.clientX - rect.left;
                    //     this.mouse.y = e.clientY - rect.top;
                    //     this.mouse.active = true;
                    // });

                    // // 鼠标离开
                    // this.container.addEventListener('mouseleave', () => {
                    //     this.mouse.active = false;
                    // });

                    // 点击打散
                    // this.container.addEventListener('click', () => {
                    //     this.particles.forEach(p => {
                    //         const angle = Math.random() * Math.PI * 2;
                    //         p.xa += Math.cos(angle) * CONFIG.SCATTER_FORCE;
                    //         p.ya += Math.sin(angle) * CONFIG.SCATTER_FORCE;
                    //     });
                    // });

                    // 窗口缩放
                    window.addEventListener('resize', () => {
                        this.updateSize();
                        this.createParticles();
                    });
                }

                // 清理
                cleanup() {
                    cancelAnimationFrame(this.animationFrameId);
                    this.container.remove();
                }
            }

            return {
                init: () => {
                    new ParticleSidebar('left');
                    new ParticleSidebar('right');
                }
            };
        })();
    }

    // 初始化
    if (document.readyState === 'complete') {
        DUAL_SIDEBAR_PARTICLE.init();
    } else {
        window.addEventListener('load', DUAL_SIDEBAR_PARTICLE.init);
    }

    // 页面卸载清理
    window.addEventListener('beforeunload', () => {
        document.querySelectorAll('.particle-sidebar').forEach(el => el.remove());
    });
})();